﻿using System;
using System.Windows.Controls;
using System.Windows.Input;

namespace Coding4Fun.PhoneControls
{
    /// <summary>
    /// A TextBox descendant that only accepts integer input.  The default keyboard editor is the Digit keyboard
    /// </summary>
    public class IntegerTextBox: TextBox
    {
        private readonly Key[] _num = new Key[] {Key.Back, Key.D0, Key.D1, Key.D2, Key.D3, Key.D4,
                       Key.D5, Key.D6, Key.D7, Key.D8, Key.D9 };


        /// <summary>
        /// Initializes a new instance of the <see cref="IntegerTextBox" /> class.  The text alignment is set to right alignment and the Digits keyboard is the default editor
        /// </summary>
        public IntegerTextBox()
        {
            InputScope = new InputScope();
            InputScope.Names.Add(new InputScopeName { NameValue = InputScopeNameValue.Digits });

            TextAlignment = System.Windows.TextAlignment.Right;
        }

        /// <summary>
        /// Called when <see cref="E:System.Windows.UIElement.KeyDown" /> event occurs.  The only keys accepted are 0-9 and the backspace key
        /// </summary>
        /// <param name="e">The data for the event.</param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (Array.IndexOf(_num, e.Key) == -1)
            {
                e.Handled = true;
            }

            base.OnKeyDown(e);
        }
    }
}
